package io.github.uicdb.et.capability;

import io.github.uicdb.et.ModElements;
import io.github.uicdb.et.fluid.ElementStream;
import lombok.RequiredArgsConstructor;
import net.neoforged.neoforge.fluids.FluidStack;
import net.neoforged.neoforge.fluids.capability.IFluidHandler;

@RequiredArgsConstructor
public class FluidAsElemental implements IElementalHandler {
    final IFluidHandler fluidHandler;

    @Override
    public int drainElemental(int requirement, ModElements type, ElementalAction action) {
        return fluidHandler.drain(new FluidStack(type.getElemental().getFluidSource(), requirement), action.execute() ? IFluidHandler.FluidAction.EXECUTE : IFluidHandler.FluidAction.SIMULATE).getAmount();
    }

    @Override
    public boolean hasElemental(ModElements type) {
        for (int i = 0; i < fluidHandler.getTanks(); i++) {
            FluidStack stack = fluidHandler.getFluidInTank(i);
            if (stack.getFluid() instanceof ElementStream.Source source && source.isSame(type.getElemental().getFluidSource().get())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int fillElemental(int requirement, ModElements type, ElementalAction action) {
        return fluidHandler.fill(new FluidStack(type.getElemental().getFluidSource(), requirement), action.execute() ? IFluidHandler.FluidAction.EXECUTE : IFluidHandler.FluidAction.SIMULATE);
    }

    @Override
    public int getElementalCapacity(ModElements modElements) {
        return fluidHandler.getTankCapacity(modElements.getIndex());
    }

    @Override
    public int getElemental(ModElements modElements) {
        return fluidHandler.getFluidInTank(modElements.getIndex()).getAmount();
    }

    @Override
    public void removeElemental(ModElements value) {
        var index = value.getIndex();
        fluidHandler.drain(fluidHandler.getFluidInTank(index), IFluidHandler.FluidAction.EXECUTE);
    }

    @Override
    public void setElemental(ModElements modElements, int value) {
        removeElemental(modElements);
        fillElemental(value,modElements,ElementalAction.EXECUTE);
    }
}
